import React, { useContext, useEffect, useRef, useState } from "react";
import classNames from "classnames";
import { ThemeContext } from "../theme";
import HeaderTabsContext, { ContextType } from "./context";
import useStyles from "./styles";
import type { HeaderTabProps, HeaderTabPaneProps } from "./type";

const URL_SEARCH_TAB_KEY = "_h_tab";

function HeaderTab({
  children,
  style,
  className,
  key,
  value,
  syncUrl = true,
  onChange,
}: HeaderTabProps) {
  const { fontSize } = useContext(ThemeContext);
  const classes = useStyles({ fontSize });
  const tabsRef = useRef<Array<string>>([]);
  const { searchParams } = new URL(location.href);
  const defaultValue = value || "";

  const [context, setContext] = useState<ContextType>({
    tabs: [],
    activeTitle: searchParams.get(key || URL_SEARCH_TAB_KEY) || defaultValue,
    addPane: (title) => {
      const hasInclude = tabsRef.current.includes(title);
      if (hasInclude) {
        console.error("ct0-Warning: Title should be unique");
        return;
      }
      tabsRef.current = [...tabsRef.current, title];

      setContext({
        ...context,
        tabs: tabsRef.current,
        activeTitle: context.activeTitle || tabsRef.current[0],
      });
    },
  });

  useEffect(() => {
    if (value) changeTab(value);
  }, [value]);

  const changeTab = (title: string) => {
    setContext({ ...context, tabs: tabsRef.current, activeTitle: title });
    const href = location.href.split("?")[0];
    const newUrl = `${href}?${URL_SEARCH_TAB_KEY}=${title}`;
    history.replaceState("", "", newUrl);
  };

  const handleClick = (title: string) => {
    if (typeof value == "undefined" && syncUrl) changeTab(title);
    onChange?.(title);
  };

  return (
    <HeaderTabsContext.Provider value={context}>
      <div className={classNames(classes.headerTab, className)} style={style}>
        <div className={classes.tabs}>
          <div className={classes.tabsPanel}>
            {context.tabs.map((title, idx) => (
              <div
                role="tab"
                key={idx}
                className={classNames(
                  classes.tab,
                  idx === 0 && classes.first,
                  idx === context.tabs.length - 1 && classes.last,
                  title === context.activeTitle && classes.active
                )}
                onClick={() => handleClick(title)}
              >
                {title}
              </div>
            ))}
          </div>
        </div>
        <div className={classes.children}>{children}</div>
      </div>
    </HeaderTabsContext.Provider>
  );
}

function HeaderTabPane({ title, children }: HeaderTabPaneProps) {
  const context = useContext(HeaderTabsContext);
  useEffect(() => {
    if (context === null) {
      console.error(
        "ct0-Warning: HeaderTabsPane should be used with HeaderTabs"
      );
      return;
    }
    context.addPane(title);
  }, []);
  return <>{context && context.activeTitle === title && children}</>;
}

HeaderTab.Pane = HeaderTabPane;

export { HeaderTabPane };

export default HeaderTab;
